<!-- src/App.vue -->
<template>
  <div id="app">
    <!-- 全局加载状态 -->
    <div v-if="globalLoading" class="global-loading">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <p class="loading-text">加载中...</p>
      </div>
    </div>

    <!-- 主内容区域 -->
    <router-view />

    <!-- 全局通知容器 -->
    <div id="global-notifications"></div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'

export default {
  name: 'App',
  setup() {
    const router = useRouter()
    const authStore = useAuthStore()
    const globalLoading = ref(true)

    // 初始化应用
    const initializeApp = async () => {
      try {
        console.log('🚀 初始化应用...')

        // 检查认证状态
        const isAuthenticated = await authStore.initializeAuth()
        console.log('🔐 认证状态:', isAuthenticated ? '已认证' : '未认证')

        // 如果是登录页面且已认证，跳转到仪表板
        const currentPath = window.location.pathname
        if (isAuthenticated && currentPath === '/login') {
          console.log('🔄 已认证用户访问登录页，跳转到仪表板')
          await router.replace('/dashboard')
        }

      } catch (error) {
        console.error('❌ 应用初始化失败:', error)
      } finally {
        // 延迟隐藏加载状态，确保平滑过渡
        setTimeout(() => {
          globalLoading.value = false
        }, 500)
      }
    }

    // 监听路由变化
    const setupRouterGuard = () => {
      router.beforeEach((to, from, next) => {
        console.log(`🛣️ 路由跳转: ${from.path} -> ${to.path}`)

        // 如果正在加载，允许路由跳转但显示加载状态
        if (globalLoading.value) {
          console.log('⏳ 应用正在加载，允许路由跳转')
          next()
          return
        }

        const isAuthenticated = authStore.isAuthenticated
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

        console.log('🔐 路由守卫检查:', {
          目标路由: to.path,
          需要认证: requiresAuth,
          当前认证状态: isAuthenticated
        })

        if (requiresAuth && !isAuthenticated) {
          console.log('🚫 未认证访问受保护路由，跳转到登录页')
          next('/login')
        } else if (to.path === '/login' && isAuthenticated) {
          console.log('✅ 已认证用户访问登录页，跳转到仪表板')
          next('/dashboard')
        } else {
          console.log('✅ 允许路由访问')
          next()
        }
      })

      // 路由错误处理
      router.onError((error) => {
        console.error('❌ 路由错误:', error)
        // 可以在这里添加错误上报或用户提示
      })
    }

    // 显示全局通知
    const showNotification = (message, type = 'info') => {
      const notifications = document.getElementById('global-notifications')
      if (notifications) {
        const notification = document.createElement('div')
        notification.className = `global-notification ${type}`
        notification.innerHTML = `
          <span class="notification-message">${message}</span>
          <button class="notification-close" onclick="this.parentElement.remove()">×</button>
        `
        notifications.appendChild(notification)

        // 3秒后自动移除
        setTimeout(() => {
          if (notification.parentElement) {
            notification.remove()
          }
        }, 3000)
      }
    }

    // 暴露全局方法（可选）
    window.showAppNotification = showNotification

    onMounted(async () => {
      console.log('🎉 App.vue 挂载完成')
      await initializeApp()
      setupRouterGuard()
    })

    // 监听认证状态变化
    watch(
        () => authStore.isAuthenticated,
        (newVal, oldVal) => {
          console.log(`🔄 认证状态变化: ${oldVal} -> ${newVal}`)
          if (!newVal && oldVal) {
            // 从已认证变为未认证
            showNotification('登录已过期，请重新登录', 'warning')
          }
        }
    )

    return {
      globalLoading
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
  'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
  sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-color: #f5f5f5;
  color: #333;
}

#app {
  min-height: 100vh;
}

/* 全局加载状态样式 */
.global-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.95);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  backdrop-filter: blur(5px);
}

.loading-content {
  text-align: center;
  background: white;
  padding: 30px 40px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  border: 1px solid #e1e5e9;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #666;
  font-size: 14px;
  margin: 0;
}

/* 全局通知样式 */
#global-notifications {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 10000;
  max-width: 400px;
}

.global-notification {
  background: white;
  padding: 12px 16px;
  margin-bottom: 10px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-left: 4px solid #1890ff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  animation: slideIn 0.3s ease-out;
}

.global-notification.success {
  border-left-color: #52c41a;
}

.global-notification.warning {
  border-left-color: #faad14;
}

.global-notification.error {
  border-left-color: #ff4d4f;
}

.notification-message {
  flex: 1;
  margin-right: 10px;
  font-size: 14px;
}

.notification-close {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.notification-close:hover {
  color: #666;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 全局滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 全局按钮重置 */
button {
  font-family: inherit;
  outline: none;
}

/* 全局输入框样式 */
input, select, textarea {
  font-family: inherit;
  outline: none;
}

/* 全局链接样式 */
a {
  color: inherit;
  text-decoration: none;
}

/* 全局工具类 */
.text-center {
  text-align: center;
}

.text-left {
  text-align: left;
}

.text-right {
  text-align: right;
}

.mt-1 { margin-top: 8px; }
.mt-2 { margin-top: 16px; }
.mt-3 { margin-top: 24px; }
.mb-1 { margin-bottom: 8px; }
.mb-2 { margin-bottom: 16px; }
.mb-3 { margin-bottom: 24px; }
.ml-1 { margin-left: 8px; }
.ml-2 { margin-left: 16px; }
.mr-1 { margin-right: 8px; }
.mr-2 { margin-right: 16px; }

.p-1 { padding: 8px; }
.p-2 { padding: 16px; }
.p-3 { padding: 24px; }

/* 响应式设计 */
@media (max-width: 768px) {
  .loading-content {
    padding: 20px 30px;
    margin: 20px;
  }

  #global-notifications {
    left: 10px;
    right: 10px;
    top: 10px;
  }

  .global-notification {
    padding: 10px 12px;
  }
}
</style>